package com.tyy.springconcurrency.demos.web.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.retry.support.RetryTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Service
public class ApiServiceWithStatusCode {
    @Autowired
    private RetryTemplate retryTemplate;

    public String sendRequest(String urlStr) throws IOException {
        return retryTemplate.execute(retryContext -> {
            URL url = new URL(urlStr);
            System.out.println("Sending request to " + urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            switch (responseCode) {
                case HttpURLConnection.HTTP_OK:
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();
                    return response.toString();
                case HttpURLConnection.HTTP_BAD_REQUEST:
                    throw new IllegalArgumentException("请求参数有误，错误码: 400");
                case HttpURLConnection.HTTP_UNAUTHORIZED:
                    throw new SecurityException("未授权访问，错误码: 401");
                case HttpURLConnection.HTTP_FORBIDDEN:
                    throw new SecurityException("禁止访问，错误码: 403");
                case HttpURLConnection.HTTP_NOT_FOUND:
                    return "请求的资源未找到，错误码: 404";
                    // throw new IllegalArgumentException("请求的资源未找到，错误码: 404");
                case HttpURLConnection.HTTP_INTERNAL_ERROR:
                    throw new IOException("服务器内部错误，错误码: 500");
                default:
                    throw new IOException("未知状态码: " + responseCode);
            }
        });
    }
}